<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
<!--      <el-form-item label="演员姓名">-->
<!--        <el-input placeholder="请输入" style="width:220px;"-->
<!--                  v-model="searchFrom.name"/>-->
<!--      </el-form-item>-->
      <el-form-item label="演员姓名">
        <el-select v-model="searchFrom.name"
                   clearable
                   filterable
                   style="width:220px;"
                   @change="search"
                   placeholder="请输入">
          <el-option
              v-for="item in tableData"
              :label="item.name"
              :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="国籍">
        <el-select v-model="searchFrom.nationality"
                   style="width:220px;"
                   placeholder="请选择国籍">
          <el-option
              v-for="item in nationalityList"
              :label="item.label"
              :value="item.value"
              @change="search">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
      <el-button type="success" style="margin-right: 20px;float: right" @click="addActor">新增演员</el-button>
    </el-form>

  </el-card>

  <div style="height: 560px;">
    <el-scrollbar height="560px">
      <el-row :gutter="10" style="margin: 0 20px">
        <el-col :span="8" v-for="item in paginatedData">
          <el-card style="margin-top: 5px; border-radius: 10px;">
            <el-row :gutter="5">
              <el-col :span="10">
                <el-avatar style="width: 120px; height: 120px">
                  <el-image :src="BASE_URL + item.poster" alt="Actor poster"/>
                </el-avatar>
              </el-col>
              <el-col :span="10">
                <p v-if="item.name != null">{{ item.name }}</p>
                <p v-if="item.englishName != null">{{ item.englishName }}</p>
                <p>{{ nationalityFormatter(item,null,item.nationality) }}</p>
              </el-col>
              <el-col :span="4">
                  <el-icon
                      size="16"
                      color="red"
                      style="margin-right: 5px;float: right"
                      @click="deleteActor(item.id)"><CircleCloseFilled /></el-icon>

                <br>
                <el-button type="primary" size="small"
                           style="margin-top: 100px;float: right"
                           @click="editActor(item.id)">编辑</el-button>


              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-scrollbar>
  </div>
  <el-card style="margin:10px 20px 0 20px;">
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-left: 35%;"
    />
  </el-card>

  <el-dialog :title="actorTitle"
             v-model="actorVisible"
             style="width:800px; padding:40px;"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="演员姓名">
            <el-input placeholder="请输入演员姓名"
                      v-model="saveFrom.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="演员英文名">
            <el-input placeholder="请输入演员英文名"
                      v-model="saveFrom.englishName"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="演员国籍">
            <el-select v-model="saveFrom.nationality"
                       placeholder="请选择演员国籍">
              <el-option
                  v-for="item in nationalityList"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="演员照片">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img :src="dialogImageUrl"
                   :alt="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button type="danger" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveActor">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import {Avatar} from "@element-plus/icons-vue";

const nationalityList = ref([]);
onMounted(() => {
  loadDictOptions(nationalityList, 'nationality');
});
const nationalityFormatter = (row, column, cellValue, index) => {
  if (!nationalityList.value) {
    return cellValue;
  }
  for (let item of nationalityList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tableData = ref([]);

const currentPage = ref(1);// 默认显示页码
const pageSize = ref(9); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchFrom = ref({
  name: '',
  nationality: ''
});

const search = () => {
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/actor/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  search();
})
const resetSearch = () => {
  searchFrom.value = {
    name: '',
    nationality: ''
  }
  search();
}
const actorVisible = ref(false);
const actorTitle = ref('新增演员');
const saveFrom = ref({
  name: '',
  englishName: '',
  nationality: '',
  poster: '',
});
const cleanAll = () => {
  saveFrom.value = {
    name: '',
    englishName: '',
    nationality: '',
    poster: '',
  };
  fileList.value = [];
}
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/
const addActor = () => {
  actorVisible.value = true;
  actorTitle.value = '新增导演';

}

const saveActor = () => {

  if (saveFrom.value.name===null || saveFrom.value.name===''){
    errorInfo('请输入演员姓名');
    return;
  }
  if (saveFrom.value.nationality===null || saveFrom.value.nationality===''){
    errorInfo('请选择演员国籍');
    return;
  }

  // if (fileList.value.length === 0) {
  //   errorInfo('请上传演员海报');
  //   return;
  // }


  saveFrom.value.poster = fileList.value[0].response.data;
  let data = qs.stringify(saveFrom.value);
  axios.post(BASE_URL + '/v1/actor/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          actorVisible.value = false;
          cleanAll();
          search();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })

}
const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    cleanAll();
    actorVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}
const editActor = (id) => {
  actorVisible.value = true;
  actorTitle.value = '编辑信息';
  axios.get(BASE_URL + '/v1/actor/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveFrom.value = response.data.data[0];
          fileList.value = [{
            url: BASE_URL + saveFrom.value.poster,
            response: {
              data: saveFrom.value.poster
            }
          }]
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}

const deleteActor = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/actor/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
      Info('已取消删除')
  });
}
</script>

<style scoped>

</style>